package com.work.account.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.work.account.service.AccountService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("account")
public class AccountController {

    @Resource
    private AccountService accountService;

    @Value("${server.port}")
    private String serverPort;

    /**
     * 只有被标注了sentinelResource的方法，才会被控制台捕获
     */
    @SentinelResource(value = "account-reduce", blockHandler = "blockExceptionHandler", fallback = "fallbackExceptionHandler")
    @RequestMapping("/reduce")
    public Boolean reduce(String userId, int money) {
/*        if (Math.random() >= 0.5 || Math.random() < 0.5) {
            throw new RuntimeException("异常");
        }*/
        System.out.println("----server.port:" + serverPort);
        accountService.reduce(userId, money);
        return true;
    }

    @SentinelResource(value = "account-add", blockHandler = "exceptionHandler")
    @GetMapping("/add")
    public Boolean add(String userId, int money) {
        accountService.add(userId, money);
        return true;
    }

    public Boolean blockExceptionHandler(String userId, int money, BlockException ex) {
        System.out.println("---block-loading---");
        return false;
    }

    public Boolean fallbackExceptionHandler(String userId, int money) {
        System.out.println("---fallback-loading---");
        return false;
    }

}
